import json
import numpy as np
import networkx as nx
from switchesalgo import allocate_switches_with_es
from topo1 import build_hybrid_topology_shared_tor


# ------------------ 核心函数封装 -------------------
def load_traffic_data(filename, target_timestamps):
    """加载指定时间戳的流量数据"""
    with open(filename, 'r') as f:
        data = json.load(f)

    traffic_data = {}
    for record in data:
        ts = record['timestamp']
        if ts in target_timestamps:
            traffic_data[ts] = {
                'matrix': np.array(record['matrix']),
                'type': record['type']
            }
    return traffic_data


def matrix_to_communication_pairs(matrix, node_prefix="ToR"):
    """将流量矩阵转换为通信对字典"""
    pairs_dict = {}
    rows, cols = matrix.shape
    for i in range(rows):
        for j in range(cols):
            src = f"{node_prefix}{i + 1}"
            dst = f"{node_prefix}{j + 1}"
            pairs_dict[(src, dst)] = float(matrix[i][j])
    return pairs_dict


def calculate_optimal_paths(topology, traffic_pairs, traffic_demand,
                            tor_nodes, os_nodes, threshold):
    """计算给定流量的最优路径"""
    switches, paths = allocate_switches_with_es(
        topology, traffic_pairs, traffic_demand,
        tor_nodes, os_nodes, threshold
    )
    return paths


def analyze_network_performance(topology, base_paths, hybrid_paths, hybrid_demand):
    """分析网络性能并输出结果"""
    # 初始化网络拓扑副本避免修改原始数据
    G = topology.copy()

    # 执行路径优化
    recon_paths, delays, static_delays = optimize_reconfiguration(
        hybrid_demand, G, base_paths, hybrid_paths
    )

    # 输出重构路径结果
    print("\n需要重构的通信对及电网络路径：")
    for pair, path in recon_paths.items():
        if path:
            print(f"{pair}: 电网络路径 {path}，最大时延 {delays[pair]:.2f} ms")
        else:
            print(f"{pair}: 无可用电路径")

    # 输出静态路径结果
    print("\n不需要重构的通信对及路径：")
    for pair in static_delays:
        if pair not in recon_paths:
            print(f"{pair}: 光网络路径 {base_paths[pair]}，最大时延 {static_delays[pair]:.2f} ms")

    # 输出链路状态
    print("\n==================链路剩余容量=====================")
    for u, v, data in G.edges(data=True):
        if 'capacity' in data:
            print(f"链路 {u}→{v}: {data['capacity']:.2f} Gbps")

    return recon_paths, delays, static_delays


# ------------------ 业务逻辑函数 -------------------
def main_workflow():
    # 初始化网络拓扑
    G = build_hybrid_topology_shared_tor(num_tor=4)

    # 加载流量数据
    traffic_data = load_traffic_data(
        'traffic_simulation.json',
        target_timestamps=[0.12, 5.19]
    )

    # 处理基础流量
    base_matrix = traffic_data[0.12]['matrix']
    base_demand = matrix_to_communication_pairs(base_matrix)
    base_pairs = [pair for pair, d in base_demand.items() if d > 0]

    # 处理混合流量
    hybrid_matrix = traffic_data[5.19]['matrix']
    hybrid_demand = matrix_to_communication_pairs(hybrid_matrix)
    hybrid_pairs = [pair for pair, d in hybrid_demand.items() if d > 0]

    # 计算基础路径
    base_paths = calculate_optimal_paths(
        G, base_pairs, base_demand,
        tor_nodes={"ToR1", "ToR2", "ToR3", "ToR4"},
        os_nodes={"os1", "os2", "os3", "os4"},
        threshold=18
    )

    # 计算混合路径
    hybrid_paths = calculate_optimal_paths(
        G, hybrid_pairs, hybrid_demand,
        tor_nodes={"ToR1", "ToR2", "ToR3", "ToR4"},
        os_nodes={"os1", "os2", "os3", "os4"},
        threshold=40
    )

    # 性能分析
    return analyze_network_performance(G, base_paths, hybrid_paths, hybrid_demand)


# ------------------ 主程序入口 -------------------
if __name__ == "__main__":
    # 执行完整工作流
    recon_paths, delays, static_delays = main_workflow()

    # 计算最终时延
    total_delay = max(
        max(delays.values(), default=0),
        max(static_delays.values(), default=0)
    )
    print(f"\n系统最终完成时延: {total_delay:.2f} ms")